//
//  LicensePlateContentViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/4/8.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "V4LicensePlateContentViewController.h"
#import "RHTableView.h"
#import "MessageEvaluationTableViewCell.h"
#import "MessageCircleFriendsTableViewCell.h"
#import "TextKeyboardView.h"
#import "SelectWebUrlViewController.h"
#import <WebKit/WebKit.h>
#import "WebImagesViewController.h"
#import "V4ShareShowView.h"

@interface V4LicensePlateContentViewController ()<MessageCircleFriendsTableViewCellDelegate,MessageEvaluationTableViewCellDelegate,UIAlertViewDelegate,WKNavigationDelegate>{
    //    RHTableView *tableViewLeft;
    NSInteger ftempCircleFriends;
    //    NSIndexPath *circleFriendsIndexPath;
    //    TextKeyboardView *textKeyboard;
    WKWebView *_webContentView;
    NSString *strTempUrl;
    BOOL boolPopRefresh;
    //    UIView *viewHeaderBG;
    float f_tempKeyBoard;
//    UIButton *_btnCollection;
    
    NSMutableArray *arrayImages;
    
    
    
}

@property(nonatomic,strong)NSDictionary*Insurancedic;
@end

@implementation V4LicensePlateContentViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTabelViews];
    
    if ([self.userInfo isEqualToString:@"Insurance"]) {
        krequestParam
        [dictparam setObject:[self.otherInfo objectForJSONKey:@"id"] forKey:@"id"];
        
        [NetEngine createGetAction_LJ:[NSString stringWithFormat:@"products/details%@",dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
            if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
                _Insurancedic=[resData objectForJSONKey:@"data"];
            }else{
                
            }
        }];
    }
}
-(void)initTabelViews{
    arrayImages=[NSMutableArray new];
    [self rightButton:nil image:@"shareicon" sel:@selector(rightBUttonClicked)];
    self.navrightButton.frame=CGRectMake(kScreenWidth-44, 20, 44, 44);

    WKWebView *webContentView=[[WKWebView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kContentHeight-44)];

    _webContentView=webContentView;
    //    webContentView.scalesPageToFit = YES;//自动对页面进行缩放以适应屏幕
    webContentView.navigationDelegate=self;
    strTempUrl=[self.otherInfo valueForJSONStrKey:@"url"];
    if (strTempUrl.length>4) {
        strTempUrl= [[[strTempUrl lowercaseString] substringToIndex:4] isEqualToString:@"http"]?strTempUrl:[NSString stringWithFormat:@"http://%@",strTempUrl];
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strTempUrl]];
    [webContentView loadRequest:request];
    //    webContentView.scrollView.scrollEnabled=NO;
    [self.view addSubview:webContentView];
    
    
    UIView *viewBottom=[[UIView alloc] initWithFrame:CGRectMake(0, YH(webContentView), kScreenWidth, 44)];
    viewBottom.backgroundColor=RGBCOLOR(56, 58, 75);
    viewBottom.autoresizingMask=UIViewAutoresizingFlexibleTopMargin;
    [self.view addSubview:viewBottom];
    
    UIButton *btnLeft=[RHMethods buttonWithFrame:CGRectMake(0, 0, kScreenWidth, 44) title:@"  电话咨询" image:@"phoneicon070116" bgimage:nil];
    [btnLeft addTarget:self action:@selector(telButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [btnLeft setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [viewBottom addSubview:btnLeft];
    
    
//        UIButton *btnRight=[RHMethods buttonWithFrame:CGRectMake(kScreenWidth/2, 0, kScreenWidth/2, 44) title:@"  参与评论" image:@"tiwenicon070116" bgimage:nil];
//        [btnRight addTarget:self action:@selector(twButtonClicked) forControlEvents:UIControlEventTouchUpInside];
//        [btnRight setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [viewBottom addSubview:btnRight];
//    
//        UIView *viewLine=[[UIView alloc] initWithFrame:CGRectMake(kScreenWidth/2, 12, 1, 20)];
//        viewLine.backgroundColor=[UIColor whiteColor];
//        [viewBottom addSubview:viewLine];
}

#pragma mark button
-(void)backButtonClicked:(id)sender{
    [_webContentView stopLoading];
    _webContentView.navigationDelegate=nil;
    _webContentView=nil;
    [super backButtonClicked:sender];
}
-(void)collectionButtonClicked{
//    //收藏
////    _btnCollection.selected=!_btnCollection.selected;
//    NSString *urls=[NSString stringWithFormat:XKFnewscollection,[[Utility Share] userId],[[Utility Share] userToken],[self.otherInfo valueForJSONStrKey:@"id"],_btnCollection.selected?@"1":@"0"];
//    if ([self.userInfo isEqualToString:@"Insurance"]) {
//        urls=[NSString stringWithFormat:XKFV3homescollection,[[Utility Share] userId],[[Utility Share] userToken],[self.otherInfo valueForJSONStrKey:@"id"],_btnCollection.selected?@"1":@"0"];
//    }
//    [NetEngine createGetAction_LJ:urls onCompletion:^(id resData, BOOL isCache) {
//        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
//            [self backRefreshData];
//        }else{
////            _btnCollection.selected=!_btnCollection.selected;
//            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
//        }
//    }];
    
}
-(void)rightBUttonClicked{
    //分享
    /*
     {
     "src": "/upload/tumour/1/1478856592.jpg",
     "title": "出现肿瘤别慌",
     "descr": "出现肿瘤别慌",
     "url": "http://www.jiusheng.com/wappage/news_detail?id=1"
     }
     
     */
    NSDictionary *dct=[self.otherInfo objectForJSONKey:@"sharedata"];
    NSMutableDictionary *dic=[NSMutableDictionary new];
    [dic setValue:[dct valueForJSONStrKey:@"pic"] forKey:@"src"];
    [dic setValue:[dct valueForJSONStrKey:@"title"] forKey:@"title"];
    [dic setValue:[dct valueForJSONStrKey:@"content"] forKey:@"descr"];
    [dic setValue:[dct valueForJSONStrKey:@"url"] forKey:@"url"];
    
    
    NSMutableDictionary*dictparam;
    
    if ([self.userInfo isEqualToString:@"Insurance"]) {
        
       dictparam =[NSMutableDictionary new];
//        [dictparam setValue:@"1" forKey:@"type"];
        [dictparam setObject:[NSString stringWithFormat:@"%@",[self.otherInfo valueForJSONStrKey:@"iscollection"]] forKey:@"iscollection"];
        if (_Insurancedic) {
            
            [dictparam setObject:[NSString stringWithFormat:@"%@",[_Insurancedic valueForJSONStrKey:@"iscollection"]] forKey:@"iscollection"];
        }
        [dictparam setObject:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"id"];
//        [dictparam setObject:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"id"];
//        ![[self.otherInfo valueForJSONStrKey:@"iscollection"] isEqualToString:@"0"]
    }else{
        [dictparam setValue:@"2" forKey:@"type"];
    }
    [dictparam setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"objid"];
    
    
    [V4ShareShowView showMeWithShareDic:dic WithCollectiondic:dictparam CallBackBlock:^(id data, int status, NSString *msg) {
        if (status==200) {
            if ([data isEqualToString:@"收藏"]) {
//                 [self backRefreshData];
//                        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
//                            [self backRefreshData];
//                        }else{
//                //            _btnCollection.selected=!_btnCollection.selected;
////                            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
//                        }
            }else{
                
                [self shareStatistics];
            }
        }
        
    }];
    
//    [[Utility Share] showShareData:dic suc:^(NSInteger NoSuc) {
//        if (NoSuc==1) {
//            [SVProgressHUD showSuccessWithStatus:@"分享成功！"];
//            [self shareStatistics];
//        }
//    }];
}
-(void)shareStatistics{
    krequestParam
    if ([self.userInfo isEqualToString:@"Insurance"]) {
        [dictparam setValue:@"1" forKey:@"type"];
    }else{
        [dictparam setValue:@"2" forKey:@"type"];
    }
    [dictparam setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"objid"];
    [NetEngine createGetAction_LJ:[NSString stringWithFormat:@"%@%@",XKFV3usershare,dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
        //        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
        //
        //        }else{
        //        }
    }];
}
#pragma mrak button
-(void)telButtonClicked{
    DLog(@"\n\n\n拨号：%@\n\n\n",[self.otherInfo valueForJSONStrKey:@"telephone"]);
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSString *telUrl = [NSString stringWithFormat:@"tel:%@",[self.otherInfo valueForJSONStrKey:@"telephone"]];
    NSURL *telURL =[NSURL URLWithString:telUrl];// 貌似tel:// 或者 tel: 都行
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];
}
-(void)twButtonClicked{
    //    circleFriendsIndexPath=nil;
    //    textKeyboard.textSend.placeholder=@"参与评论...";
    //    __weak LicensePlateContentViewController * viewC1=self;
    //    [textKeyboard setValueForDictionary:nil indexPath:nil sendText:^(NSDictionary *dict, NSIndexPath *indexPath, NSString *txtSend) {
    //        [viewC1 sendEvaluationData:txtSend selectIndex:nil];
    //
    //    }];
}
//分离URL参数
-(NSMutableDictionary *)dicSeparatedUrl:(NSString *)strurl{
    //获取问号的位置，问号后是参数列表
    NSRange range = [strurl rangeOfString:@"?"];
    NSLog(@"参数列表开始的位置：%d", (int)range.location);
    
    //获取参数列表
    NSString *propertys = [strurl substringFromIndex:(int)(range.location+1)];
    NSLog(@"截取的参数列表：%@", propertys);
    
    //进行字符串的拆分，通过&来拆分，把每个参数分开
    NSArray *subArray = [propertys componentsSeparatedByString:@"&"];
    NSLog(@"把每个参数列表进行拆分，返回为数组：n%@", subArray);
    
    //把subArray转换为字典
    //tempDic中存放一个URL中转换的键值对
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithCapacity:4];
    
    for (int j = 0 ; j < subArray.count; j++)
    {
        if ([subArray[j] notEmptyOrNull]) {
            //在通过=拆分键和值
            NSArray *dicArray = [subArray[j] componentsSeparatedByString:@"="];
            if ([dicArray count]>1) {
                //给字典加入元素
                [tempDic setObject:dicArray[1] forKey:dicArray[0]];
            }else if([dicArray count]){
                [tempDic setObject:@"" forKey:dicArray[0]];
            }
        }
    }
    NSLog(@"打印参数列表生成的字典：n%@", tempDic);
    
    return tempDic;
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    strTempUrl= [navigationAction.request.URL absoluteString];
    if ( [strTempUrl rangeOfString:@"&action=userCard"].length>0) {
        //牌照详情-查看个人名片
        NSDictionary *dicUser = [self dicSeparatedUrl:[strTempUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSMutableDictionary *dicCard=[NSMutableDictionary new];
        [dicCard setValue:strTempUrl forKey:@"url"];
        [dicCard setValue:[dicUser valueForJSONStrKey:@"id"] forKey:@"uid"];
        [dicCard setValue:NSStringFromClass([self class]) forKey:@"controller"];
        [self pushController:[SelectWebUrlViewController class] withInfo:@"shareCard" withTitle:@" " withOther:dicCard];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    NSString *requestString = [[navigationAction.request URL] absoluteString];
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        NSInteger index_img=0;
        NSMutableArray *array=[[NSMutableArray alloc] init];
        for (int i=0 ; i<[arrayImages count];i++) {
            NSString *strImg =[arrayImages objectAtIndex:i];
            if ([strImg isEqualToString:imageUrl]) {
                index_img=i;
            }
            NSMutableDictionary *dt=[[NSMutableDictionary alloc] init];
            [dt setValue:strImg forKey:@"url"];
            [array addObject:dt];
        }
        [self pushController:[WebImagesViewController class]
                    withInfo:@"myWebView"
                   withTitle:@"查看"
                   withOther:@{@"lookImages":array,
                               @"lookSelectIndex":[NSString stringWithFormat:@"%ld",(long)index_img]}];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    //    NSURL *URL = navigationAction.request.URL;
    //    NSString *scheme = [URL scheme];
    //    if ([scheme isEqualToString:@"haleyaction"]) {
    //        [self handleCustomAction:URL];
    //        decisionHandler(WKNavigationActionPolicyCancel);
    //        return;
    //    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    DLog(@"web开始加载：%@",[webView.URL absoluteString]);
    [SVProgressHUD showWithStatus:@"加载中"];
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //js方法遍历图片添加点击事件 返回图片点击个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var image_url=\"\";\
    var index_click=0;\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    if(objs[i].getAttribute(\"data-src\")){\
    if(image_url){\
    image_url=image_url+\"__zkwap__\"+objs[i].getAttribute(\"data-src\");\
    }else{\
    image_url=objs[i].getAttribute(\"data-src\");\
    };\
    index_click++;\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.getAttribute(\"data-src\");;\
    };\
    };\
    };\
    return image_url;\
    };getImages();";
    
    
    //
    /// jsStr为要执行的js代码，字符串形式
    [webView evaluateJavaScript:jsGetImages completionHandler:^(id _Nullable resurlt, NSError * _Nullable error) {
        // 执行结果回调
        DLog(@"执行结果回调:%@",resurlt);
        [arrayImages removeAllObjects];
        if ([resurlt notEmptyOrNull]) {
            [arrayImages addObjectsFromArray:[resurlt componentsSeparatedByString:@"__zkwap__"]];
        }
        
    }];
    [SVProgressHUD dismiss];
    //     [self loadTableData];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD showImage:nil status:@"数据加载失败！"];
}

-(void)backRefreshData{
    for (id controller in self.navigationController.viewControllers) {
        if ([NSStringFromClass([controller class]) isEqualToString:@"LicensePlateViewController"]||
            [NSStringFromClass([controller class]) isEqualToString:@"UserLicensePlateViewController" ]||
            [NSStringFromClass([controller class]) isEqualToString:@"UserExtensionViewController" ]||
            [NSStringFromClass([controller class]) isEqualToString:@"V4HomeViewController" ]) {
            if ([(NSObject*)controller respondsToSelector:@selector(popRefreshData)]) {
                [controller performSelector:@selector(popRefreshData) withObject:nil afterDelay:0.01];
            }
            continue;
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
